package com.four.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.domain.Data;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.four.config.AlipayConfig;
import com.four.mapper.RegMapper;
import com.four.mapper.SchedulingMapper;
import com.four.service.SchedulingService;
import com.four.vo.PayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: WangPeng
 * @createTime: 2022/10/19 19:47
 * @description:
 * @version: v1.0
 */
@RestController
@RequestMapping("/apiPay")
public class PayController {

    @Autowired
    private  RegMapper regMapper;

    @Autowired
    private SchedulingService schedulingService;

    @RequestMapping("/pay")
    public void pay(PayVo payVo , HttpServletResponse response) throws Exception{
        Date date = new Date();
        payVo.setOrderId(new SimpleDateFormat("yyyyMMdd").format(date) + System.currentTimeMillis());
        payVo.setOrderNmae("预约挂号费");
        //传递过来的排班信息的id
        Integer schedulingId = Integer.valueOf(String.valueOf(payVo.getSchedulingId()));
//        System.out.println("~~~~~~~~~~~~~"+schedulingId);
//        payVo.setPrice("20");
        // 商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = payVo.getOrderId()+"";
        // 订单名称，必填
        String subject = payVo.getOrderNmae();
        // 付款金额，必填
        String total_amount=payVo.getPrice()+"";
        // 超时时间 可空
        String timeout_express="2m";
        // 销售产品码 必填
        String product_code="QUICK_WAP_WAY";
        /**********************/
        // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        //调用RSA签名方式
        AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
        AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();
        // 封装请求支付信息
        AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
        model.setOutTradeNo(out_trade_no);
        model.setSubject(subject);
        model.setTotalAmount(total_amount);
        model.setTimeoutExpress(timeout_express);
        model.setProductCode(product_code);
        alipay_request.setBizModel(model);
        // 设置异步通知地址
        alipay_request.setNotifyUrl(AlipayConfig.notify_url);
        // 设置同步地址
        alipay_request.setReturnUrl(AlipayConfig.return_url);

        // form表单生产
        String form = "";

        //修改排班信息表中的排班数量
        schedulingService.appointmentSubNum(schedulingId);
        try {
            // 调用SDK生成表单
            form = client.pageExecute(alipay_request).getBody();
            response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @RequestMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify( PayVo payVo,HttpServletRequest request) throws Exception {
        System.out.println("=========支付宝异步回调========");
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
            System.out.println(name + " = " + request.getParameter(name));
        }

        String outTradeNo = params.get("out_trade_no");
        String gmtPayment = params.get("gmt_payment");
        String alipayTradeNo = params.get("trade_no");
        String sign = params.get("sign");
        String content = AlipaySignature.getSignCheckContentV1(params);
        boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, AlipayConfig.ALIPAY_PUBLIC_KEY, "UTF-8"); // 验证签名
        // 支付宝验签
        if (checkSignature) {
            // 验签通过
            System.out.println("交易名称: " + params.get("subject"));
            System.out.println("交易状态: " + params.get("trade_status"));
            System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
            System.out.println("商户订单号: " + params.get("out_trade_no"));
            System.out.println("交易金额: " + params.get("total_amount"));
            System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
            System.out.println("买家付款时间: " + params.get("gmt_payment"));
            System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
            System.out.println(params.get("schedulingId"));

//            // 查询订单
//            Orders orders = ordersMapper.selectOne(outTradeNo);
//            if (orders != null) {
//                orders.setAlipayNo(alipayTradeNo);
//                orders.setPayTime(new Date());
//                orders.setState("已支付");
//                //修改订单状态
//                ordersMapper.updateById(orders);
//            }
        }
        return "success";
    }
}
